import { createRouter, createWebHistory } from 'vue-router'
import { isLoggedIn } from '@/utils/auth'
import MovieList from '@/views/MovieList.vue'
import MovieDetail from '@/views/MovieDetail.vue'
import Register from '@/views/Register.vue'
import ActivateEmail from '@/views/ActivateEmail.vue'
import Login from '@/views/Login.vue'
import ResetPassword from '@/views/ResetPassword.vue'
import PasswordReset from '@/views/PasswordReset.vue' 
import ChangePassword from '@/views/ChangePassword.vue' 
import Personal from '@/views/Personal.vue'
import Collect from '@/views/Collect.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'MovieList',
      component: MovieList
    },
    {
      path: '/movie/:id',
      name: 'MovieDetail',
      component: MovieDetail
    },
    {
      path: '/movie',
      redirect: '/'
    },
    {
      path: '/register',
      name: 'Register',
      component: Register
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/NotFound.vue')
    },
    {
      path: "/activate/:uid/:token",
      name: "ActivateEmail",
      component: ActivateEmail
    },
    {
      path: "/login",
      name: "Login",
      component: Login
    },
    {
      path: '/reset_password',
      name: 'ResetPassword',
      component: ResetPassword
    },
    {
      path: '/password_reset/:uid/:token',
      name: 'PasswordReset',
      component: PasswordReset
    },
    {
      path: "/personal",
      name: "Personal",
      component: Personal,
      meta: { requiresAuth: true }
    },
    {
      path: "/change_password",
      name: "ChangePassword",
      component: ChangePassword,
      meta: { requiresAuth: true }
    },
    {
      path: "/collect",
      name: "Collect",
      component: Collect,
      meta: { requiresAuth: true }
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 检查该路由是否需要登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查用户是否已登录
    if (!isLoggedIn()) {
      // 未登录，重定向到登录页面
      next({
        path: '/login',
        // 保存目标路由的完整路径，登录成功后跳转回来
        query: { redirect: to.fullPath }
      })
    } else {
      // 已登录，允许访问
      next()
    }
  } else {
    // 不需要登录的路由，直接访问
    next()
  }
})


export default router
